package cn._2dland.sakushi.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn._2dland.sakushi.InvalidRequestException;
import cn._2dland.sakushi.NoSuchRequestException;
import cn._2dland.sakushi.Policy;
import cn._2dland.sakushi.Sakushi;
import cn._2dland.sakushi.SakushiInfo;
import cn._2dland.sakushi.client.FanfouClient;
import cn._2dland.sakushi.jdo.PMFactory;
import cn._2dland.sakushi.jdo.Question;

/**
 * 决策Servlet
 * 负责对请求进行处理，并推送到饭否上
 * 
 * @author deadblue
 */
public class FanfouSakushiServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String statusID = req.getParameter("status_id");

		// 获取持久化管理器实例
		PersistenceManager pm = PMFactory.getPMFInstance().getPersistenceManager();
		Question q = null;

		try {
			if(statusID == null) {
				throw new Exception("无效请求，未指定状态ID！");
			}

			// 从持久化存储中读取消息
			q = pm.getObjectById(Question.class, statusID);

			// 判断消息状态
			if(q == null) {
				throw new NoSuchRequestException("找不到该状态记录");
			}
			if(q.getStatus() > 0) {
				throw new Exception("该请求已经被处理");
			}

			// 取出消息，进行决策
			String text = q.getText();
			Sakushi s = new Sakushi();
			Policy p = s.accept(q.getUserName(), text);

			String result = new StringBuffer("@").append(q.getUserName()).append(" ").append(p.getContent()).toString();
			// 将结果发送给请求者
			FanfouClient client = new FanfouClient(SakushiInfo.FANFOU_API_KEY, 
					SakushiInfo.FANFOU_OAUTH_TOKEN, SakushiInfo.FANFOU_OAUTH_SECRET);
			if(p.hasChart()) {
				client.upload(result, p.getChart(), null, SakushiInfo.FANFOU_SOURCE);
			}
			else {
				client.update(result, null, SakushiInfo.FANFOU_SOURCE);
			}

			// 标识为已处理
			q.setStatus(1);
		}
		catch (Exception e) {
			if(e instanceof InvalidRequestException) {
				// 标识为不合法消息
				if(q != null) q.setStatus(2);
			} else {
				if(q != null) q.setStatus(0);
			}

			Logger.getLogger("Sakushi").throwing("SakushiServlet", "doPost", e);
		}
		finally {
			// 释放资源
			pm.close();
		}
	}
}